package cn.e3mall.content.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.pojo.EasyUITreeNode;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.content.service.ContentCategoryService;
import cn.e3mall.mapper.TbContentCategoryMapper;
import cn.e3mall.pojo.TbContentCategory;
import cn.e3mall.pojo.TbContentCategoryExample;
import cn.e3mall.pojo.TbContentCategoryExample.Criteria;
/**
 * 内容管理service
 * @author shanqingyun
 *
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
	@Autowired
	private TbContentCategoryMapper categoryMapper;
	
	
	@Override
	public List<EasyUITreeNode> getContentCate(long parentId) {
		//根据parentID查询子节点列表
		TbContentCategoryExample categoryExample=new TbContentCategoryExample();
		Criteria criteria = categoryExample.createCriteria();
		//设置查询条件
		criteria.andParentIdEqualTo(parentId);
		//返回查询结果
		List<TbContentCategory> cateList = categoryMapper.selectByExample(categoryExample);
		//将结果转换成EasyUITreeNode的结果集
		List<EasyUITreeNode> list=new ArrayList<EasyUITreeNode>();
		
		for (TbContentCategory tbContentCategory : cateList) {
			EasyUITreeNode node=new EasyUITreeNode();
			node.setId(tbContentCategory.getId());
			node.setText(tbContentCategory.getName());
			node.setState(tbContentCategory.getIsParent()?"closed":"open");
			list.add(node);
		}
		return list;
	}

	@Override
	public E3Result addContentCategory(long parentId, String name) {
		//创建一个tbcontentcategory的pojo对象
		TbContentCategory category=new TbContentCategory();
		//设置pojo 的属性
		category.setParentId(parentId);
		category.setName(name);
		//1(正常)2(删除)
		category.setStatus(1);
		//默认排序为1
		category.setSortOrder(1);
		//新增加的节点一定是叶子节点
		category.setIsParent(false);
		category.setCreated(new Date());
		category.setUpdated(new Date());
		//插入数据库
		categoryMapper.insert(category);
		//判断父节点的isparent 是否为true 不是的话改为true
		TbContentCategory tbContentCategory = categoryMapper.selectByPrimaryKey(parentId);
		if(!tbContentCategory.getIsParent()){
			tbContentCategory.setIsParent(true);
			//更新到数据库中
			categoryMapper.updateByPrimaryKey(tbContentCategory); 
		}
		return E3Result.ok(category);
	}
	
	
	
}
